const redux = require('redux')
const initialState = {
  counter: 0,
}

// 3.reducer

function numReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, counter: state.counter + 1 }
      break
    case 'DECREMENT':
      return { ...state, counter: state.counter - 1 }
      break
    case 'ADD_NUMBER':
      return { ...state, counter: state.counter + action.num }
      break
    case 'SUB_NUMBER':
      return { ...state, counter: state.counter - action.num }
      break
    default:
      return state
  }
}

// 1.store创建时需要传入一个reducer
const Store = redux.createStore(numReducer)
// 2.action
const action1 = { type: 'INCREMENT' }
const action2 = { type: 'DECREMENT' }
const action3 = { type: 'ADD_NUMBER', num: 5 }
const action4 = { type: 'SUB_NUMBER', num: 12 }
// 对Store内部数据的变化进行订阅
Store.subscribe(() => {
  console.log('state被改变了', Store.getState())
})
// 派发action
Store.dispatch(action1)
Store.dispatch(action2)
Store.dispatch(action3)
Store.dispatch(action4)
